package com.itfreer.file.service.kindeditor;

import java.io.IOException;
import java.io.OutputStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.file.service.IObjectDownloadService;

/**
 * 定义标准的下载服务接口
 */
@Component(value="KindeditorDownloadService")
@Path("/file/kindeditor")
public class DownloadService {

	@Autowired
	private IObjectDownloadService objectDownload;
	
	/**
	 * 下载文件
	 * 
	 * @param template
	 *            模板文件
	 * @param data
	 *            模板数据
	 */
	@GET
	@Path("/download")
	@Produces({MediaType.APPLICATION_OCTET_STREAM})
	public Response download(@QueryParam("bucket") String bucketName, 
			@QueryParam("key") String objectKey) throws Exception {
		byte[] result = objectDownload.getObject(bucketName, objectKey);
		StreamingOutput stream = new StreamingOutput() {
			@Override
			public void write(OutputStream output) throws IOException, WebApplicationException {
				try {
					output.write(result);
	            } catch (Exception e) {
	                throw new WebApplicationException(e);
	            }
			}
	    };
	    return Response.ok(stream)
	    		.header("content-disposition","attachment;")
	    		.header("Cache-Control", "no-cache").build();
	}
}